<!--交易明细列表-->
<template>
  <div>
    <Dialog style="padding: 0;" :visible="visible" :title="visibleTitle" width="70%" @close="close"
            @cancel="visible = false" :footer="false">
      <el-form label-width="80px" :model="page" ref="searchForm">
        <el-row :gutter="24">
          <!-- 条件第二行 -->
          <el-col :span="12" :xs="24">
            <el-form-item :label="$t('加入时间')" prop="timeValue">
              <el-date-picker
                  v-model="page.timeValue"
                  style="width: 100%"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="~"
                  unlink-panels
                  :start-placeholder="$t('开始日期')"
                  :end-placeholder="$t('结束日期')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('APP名称')" prop="productName">
              <el-select
                  style="width: 100%"
                  v-model="page.productName"
                  clearable
              >
                <el-option
                    v-for="item in productList"
                    :key="item.productId"
                    :label="item.productName"
                    :value="item.productName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" :xs="24">
            <div style="text-align: right;display: flex; flex: 1; justify-content: flex-end;">
              <el-button type="primary" @click="getData" v-show="$permiss[459]">{{ $t('查询') }}</el-button>
              <el-button @click="resetData">{{ $t('重置') }}</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <span class="line"></span>

      <div style="text-align: right; margin-bottom: 10px;" v-show="$permiss[464]">
        <el-button type="primary" @click="isAddRecent()">{{ $t('新增交易') }}</el-button>
      </div>
      <Table row-key="id" :table-data="tableData" :page="page" :tableColumn="tableColumn"
              :loading="loading"
             @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange">
        <template slot="operate" v-if="$permiss[534]">
          <el-table-column :label="$t('操作')" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="updateUnivalent(scope.row)">{{ $t('编辑') }}
              </el-button>
            </template>
          </el-table-column>
        </template>
      </Table>

      <!--修改单价-->
      <Dialog :visible.sync="univalentVisible.isShow" :title="univalentVisible.title"
              :destroyClose="true"
              :append-body="true"
              @confirm="visibleChannelConfirm" @cancel="clearUnivalent" @close="clearUnivalent">
        <el-form label-width="100px" :model="univalentForm" ref="univalentForm" :rules="univalentRulesForm">
          <el-form-item :label="$t('渠道名称')" prop="channelName">
            <span>{{ univalentForm.channelName }}</span>
          </el-form-item>
          <el-form-item :label="$t('单价')" prop="univalent">
            <el-input maxlength="20" oninput="value = value.replace(/[^\d.]/g, '')"
                      v-model="univalentForm.univalent"/>
          </el-form-item>
          <el-form-item :label="$t('交易日期')" prop="recentTime">
            <el-date-picker
                :disabled="true"
                v-model="univalentForm.recentTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                :placeholder="$t('选择交易时间')"
            />
          </el-form-item>
        </el-form>
      </Dialog>

      <DataTrends :loan="loanData" :repayment="repaymentData"></DataTrends>
      <AddTrade :trade-visible.sync="addTradeVisible" :trade-data="addTradeModel"></AddTrade>
    </Dialog>
  </div>
</template>

<script>
import DataTrends from '../compoents/dataTrends'
import AddTrade from "@/views/channel/compoents/addTrade";
import eventBus from "@/utils/eventBus";
import {fetchRecentList, isAddRecent, updateRecent, fetchRecentPayment, fetchRecentRefund} from '@/api/channel'
import {selectProduct} from "@/api/system";
import {dateFormatSection} from "@/utils/tools";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    item: {},
    title: String
  },
  data() {
    return {
      //白名单交易列表
      page: {
        channelName: '',
        timeValue: null,
        pageNum: 1,
        pageSize: 10,
        total: 0,
        adminUserId: 0,
      },
      loading:false,
      tableData: [],
      tableColumn: [
        {label: this.$t('交易时间'), prop: 'recentTime', align: "center", width: 150},
        {label: this.$t('名单数'), prop: 'number', align: "center"},
        {label: this.$t('单价'), prop: 'univalent', align: "center"},
        {label: this.$t('注册数'), prop: 'registeredNum', align: "center"},
        {label: this.$t('申请数'), prop: 'loanNum', align: "center"},
        {label: this.$t('通过数'), prop: 'passNum', align: "center"},
        {label: this.$t('放款数'), prop: 'paymentNum', align: "center"},
        {label: this.$t('放款成本'), prop: 'paymentCost', align: "center"},
        {label: this.$t('还款数'), prop: 'refundNum', align: "center"},
        {label: 'D0' + this.$t('未还率'), prop: 'd0', align: "center"},
        {label: this.$t('逾期数'), prop: 'badDebtNum', align: "center"},
        {label: this.$t('坏账率'), prop: 'badDebtCost', align: "center"},
      ],
      //放款
      loanData: [],
      productList: [],
      //还款
      repaymentData: [],
      //新增交易
      addTradeVisible: false,
      addTradeModel: {},
      //修改单价
      univalentVisible: {
        isShow: false,
        title: '',
      },
      univalentForm: {
        adminUserId: 0,
        channelName: '',
        number: 0,
        univalent: 0,
        recentTime: ''
      },
      univalentRulesForm: {
        univalent: [
          {
            required: true, validator: (rules, value, callback) => {
              const {univalent} = this.univalentForm
              if (univalent === undefined || univalent === '') {
                return callback(new Error(this.$t('单价不能为空')))
              }
              return callback()
            }
          },
        ],
        recentTime: [
          {required: true, message: this.$t('交易日期不能为空')},
        ]
      },
    }
  },
  components: {
    DataTrends,
    AddTrade,
  },
  computed: {
    visibleTitle() {
      return this.title + ' - ' + this.$t('渠道') + this.$t('明细')
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.getData();
      }
    },
  },
  async mounted() {
    // this.getData();
    eventBus.$on('addTradeSuccessEvent', (univalent) => {
      this.item.univalent = univalent;
      this.getTableData()
    })
    selectProduct().then(res => {
      this.productList = res.data
    })
  },
  methods: {
    //白名单交易列表
    async getData() {
      this.getTableData();
      this.graphicData(1)
      this.graphicData(0)
    },

    //白名单明细交易列表
    async getTableData() {
      const timeValue = dateFormatSection(this.page.timeValue);
      const params = Object.assign({}, this.page, {
        startTime: timeValue && timeValue.length >= 1 ? timeValue[0] : undefined,
        endTime: timeValue && timeValue.length >= 2 ? timeValue[1] : undefined,
        channelName: this.item.channelName,
        adminUserId: this.item.adminUserId,
      });
      delete params.timeValue;
      this.loading =true
      const res = await fetchRecentList(params);
      if (res.code === 1) {
        const {list, total} = res.data;
        this.tableData = list.map(item => {
          if (item.badDebtCost) {
            item.badDebtCost = item.badDebtCost + '%'
          }
          return item
        });
        this.page = Object.assign({}, this.page, {
          total: total,
        })
        this.loading = false
      } else {
        this.loading = false
      }
    },

    //放款
    /**
     * 获取图形数据列表
     * @param type  1 放款 否则还款
     * @returns {Promise<void>}
     */
    async graphicData(type) {
      let api
      const timeValue = this.page.timeValue;
      const params = Object.assign({}, this.page, {
        startTime: timeValue && timeValue.length >= 1 ? timeValue[0] : undefined,
        endTime: timeValue && timeValue.length >= 2 ? timeValue[1] : undefined,
        pageNum: this.page.pageNum,
        pageSize: 30,
      });
      delete params.timeValue;
      if (type === 1) {
        api = fetchRecentPayment(params)
      } else {
        api = fetchRecentRefund(params)
      }
      const res = await api
      if (type === 1) {
        this.loanData = res.data;
      } else {
        this.repaymentData = res.data;
      }
    },
    //重置
    resetData() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        timeValue: null
      }
      this.$refs.searchForm.resetFields();
      this.getData()
    },
    //是否能交易
    async isAddRecent() {
      let data = this.item
      let model = {}
      model.channelName = data.channelName;
      model.adminUserId = data.adminUserId
      const res = await isAddRecent(model);
      if (res.code === 1) {
        this.addTrade(data)
      }
    },
    //新增交易
    addTrade(row) {
      this.addTradeModel = row
      this.addTradeVisible = true
    },
    close() {
      this.page.timeValue = null;
      this.page.productName = null;
      this.$emit('update:visible', false)
    },
    //修改单价
    updateUnivalent(data) {
      this.univalentForm = {
        id: data.id,
        adminUserId: this.item.adminUserId,
        channelName: this.item.channelName,
        number: data.number,
        univalent: data.univalent,
        recentTime: data.recentTime
      }

      this.univalentVisible = {
        isShow: true,
        title: this.$t('修改单价'),
      }
    },
    //清除单价
    clearUnivalent() {
      this.univalentForm = {
        recentTime: '',
        univalent: ''
      }
      this.univalentVisible.isShow = false
      this.$refs.univalentForm.resetFields()
    },
    visibleChannelConfirm() {
      this.$refs.univalentForm.validate(async v => {
        if (v) {
          let message = this.$t('修改成功')
          const res = await updateRecent({
            ...this.univalentForm,
            univalent: parseFloat(this.univalentForm.univalent),
            recentTime: undefined
          })
          if (res.code === 1) {
            this.$message.success(message)
            this.clearUnivalent()
            this.univalentVisible.isShow = false
            this.getTableData()
          }
        }
      })
    },
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getTableData()
    },
  },
  beforeDestroy() {
    eventBus.$off('addTradeSuccessEvent')
  }
}
</script>

<style lang="less" scoped>
.line {
  display: flex;
  flex: 1;
  background-color: #EEEEEE;
  height: 1px;
  margin-top: 20px;
  margin-bottom: 10px
}
</style>
